package com.mi.easyexceldemo.controller;

import com.mi.easyexceldemo.annotation.Result;
import com.mi.easyexceldemo.service.FilerMeaasgeService;
import com.mi.easyexceldemo.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
@Api(value = "excel的上传与下载",description = "excel的上传与下载")
public class FilerMeaasge {
    private Logger logger = LoggerFactory.getLogger(FilerMeaasge.class);

    @Value("${excelImport.path}")
    private String uploadPath;

    @Autowired
    private FilerMeaasgeService filerMeaasgeService;

    @ApiOperation(value = "导入", notes = "数据导入", httpMethod = "POST")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result importExcel(@RequestParam("file") MultipartFile file){
        String filePath = null;
        try {
            filePath = FileUtil.uploadFile(uploadPath, file);
            logger.debug("Excel数据导入，上传临时文件：" + filePath);

            String msg = filerMeaasgeService.importExcelData(filePath);
            if (StringUtils.isNotBlank(msg)) {
                return new Result<>(msg, "failure", 400);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>("导入失败", "failure", 400);
        } finally {
            FileUtil.deleteFile(filePath);
            logger.debug("删除临时文件：" + filePath);
        }
        return new Result<>("导入成功", "success", 200);
    }
}
